import React, { useEffect, useState } from "react";
import { ArrowLeft } from "@react-vant/icons";
import "./eventClick.css";
import TopNav from "../../components/TopNav/TopNav";
import { useNavigate } from "react-router";
import { Toast } from "react-vant";
import axios from "axios";

const EventClick = () => {
  const [events, setEvents] = useState([]);
  const navigate = useNavigate();

  // 获取数据
  useEffect(() => {
    const fetchEvents = async () => {
      try {
        const response = await axios.get("http://192.168.0.154:3000/my/rili");
        console.log("API response:", response.data); // 添加日志查看数据

        // 转换数据格式
        const formattedEvents = response.data.map((item, index) => ({
          id: index + 1,
          icon: getEventIcon(index),
          title: item.title || "未命名事件",
          time: formatEventTime(index),
          duration: "4h",
          direction: index % 2 === 0 ? "up" : "down",
        }));

        console.log("Formatted events:", formattedEvents); // 添加日志查看转换后的数据
        setEvents(formattedEvents);
      } catch (error) {
        console.error("获取事件失败:", error);
        Toast.fail("获取事件失败");
      }
    };

    fetchEvents();
  }, []); // 空依赖数组，确保只在组件挂载时执行一次

  // 根据索引返回不同图标
  const getEventIcon = (index) => {
    const icons = ["🌧️", "👥", "🎂", "📺"];
    return icons[index % icons.length];
  };

  // 生成时间显示
  const formatEventTime = (index) => {
    const today = new Date();
    const date = new Date(today);
    date.setDate(today.getDate() + Math.floor(index / 2));
    const timeStr = index % 2 === 0 ? "6:00 PM" : "5:00 PM";

    if (date.toDateString() === today.toDateString()) {
      return `今天 | ${timeStr}`;
    } else if (
      date.toDateString() ===
      new Date(today.setDate(today.getDate() + 1)).toDateString()
    ) {
      return `明天 | ${timeStr}`;
    } else {
      return `${date.getMonth() + 1}月${date.getDate()}日 | ${timeStr}`;
    }
  };

  return (
    <div className="event-page">
      <div className="top-nav-container">
        <TopNav />
      </div>

      <div className="recent-events">
        <div className="headerTop" onClick={() => navigate("/admin-dashboard")}>
          <ArrowLeft className="back-arrow" />
          <span>通回仪表盘</span>
        </div>

        <h2 className="section-title">最近事件</h2>

        <div className="events-list">
          {events && events.length > 0 ? (
            events.map((event) => (
              <div key={event.id} className="event-items">
                <div className="event-icons">{event.icon}</div>
                <div className="event-contents">
                  <div>
                    <div className="event-titles">{event.title}</div>
                    <div className="event-time">
                      <span>{event.time}</span>
                      <span className="duration">
                        <span className="clock">🕐</span>
                        {event.duration}
                      </span>
                    </div>
                  </div>
                  <div className={`direction-arrow ${event.direction}`}>
                    {event.direction === "up" ? "↑" : "↓"}
                  </div>
                </div>
              </div>
            ))
          ) : (
            <div className="no-events">加载中...</div>
          )}
        </div>
      </div>
    </div>
  );
};

export default EventClick;
